<?php
// +----------------------------------------------------------------------
// | huicmf [ huicmf快速开发框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2024 https://xiaohuihui.cc All rights reserved.
// +----------------------------------------------------------------------
// | Author: 小灰灰 <762229008@qq.com>
// +----------------------------------------------------------------------
// | Info:
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\model\Config as ConfigModel;
use app\common\model\Category as CategoryModel;
use think\facade\Cache;
use app\common\library\Html;
use think\facade\Db;
use think\facade\Validate;
use think\facade\View;
use libs\Tree2;

class Seo extends Base
{

    /**
     * 伪静态规则
     */
    protected $rules = [
        //['/:catname/$','/:catname/:id$.html'],
        ['/:catname/$,/:catname/list_:page$.html', '/:catname/:id$.html'],
        ['/[:lang]/:catname/$,/[:lang]/:catname/list_:page$.html', '/[:lang]/:catname/:id$.html'],
        ['/[:catdir]/:catname/$', '/[:catdir]/:catname/:id$.html'],
        ['/[:lang]/[:catdir]/:catname/$', '/[:lang]/[:catdir]/:catname/:id$.html'],
        ['/:model/:catname/$', '/:model/:id$.html'],
    ];

    /**
     * 静态生成规则
     */
    protected $htmlRules = [
        'category' => [
            // 父级栏目/子栏目/index.html|父级栏目/子栏目/index_2.html
            '/[catdir]/[list]/index.html|/[catdir]/[list]/index_[page].html',
            // 栏目名称/index.html|/栏目名称/index_2.html
            '/[list]/index.html|/[list]/index_[page].html',
        ],

        'content' => [
            // 父级栏目/子栏目/文档ID.html|父级栏目/子栏目/文档ID_1.html
            '/[catdir]/[list]/[id].html|/[catdir]/[list]/[id]_[page].html',
            // 栏目名称/文档ID.html|栏目名称/文档ID_2.html
            '/[list]/[id].html|/[list]/[id]_[page].html'
        ]
    ];

    /**
     * url 配置
     * @return string|\think\response\Json|void
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $row      = $this->request->post('row');
            $isstatic = 0;
            if ($row['url_mode'] == 0) { // 动态
                ConfigModel::where(['name' => 'url_file'])->save(['value' => $row['url_file']]);
                // 更新静态URL地址
                if (get_config('url_mode') == 2) {
                    (new Html(app()))->clearUrl();
                }
            } else {
                if ($row['url_mode'] == 1) { // 伪静态、使用内置规则
                    $index = $row['url_format'] - 1;
                    if ($index == -1) {
                        // TODO:自定义模块未开发
                        $this->error('自定义模式前往站点配置->高级配置->伪静态配置修改');
                    }
                    $rule                   = $this->rules[$row['url_format'] - 1];
                    $info                   = Db::name('config')->where(['name' => 'url_rewrite'])->find();
                    $rewrite                = json_decode($info['value'], true);
                    $rewrite['index/lists'] = $rule[0];
                    $rewrite['index/show']  = $rule[1];
                    if (($row['url_format'] == 4 || $row['url_format'] == 2) && empty($rewrite['/'])) { // 多语言
                        $newRe   = ['/' => '/[:lang]/$'];
                        $rewrite = array_merge($newRe, $rewrite);
                    } else {
                        if (in_array($row['url_format'],
                                ['1', '3', '4']) && ! empty($rewrite['/']) && $rewrite['/'] == '/[:lang]/$') {
                            unset($rewrite['/']);
                        }
                    }
                    Db::name('config')->where(['name' => 'url_rewrite'])->update(['value' => json_encode($rewrite)]);
                    // 更新静态URL地址
                    if (get_config('url_mode') == 2) {
                        Html::clearUrl();
                    }
                } else {
                    // 静态生成
                    if (empty($row['html_column_rules'])) {
                        $this->error('栏目规则不能为空');
                    }
                    if (empty($row['html_content_rules'])) {
                        $this->error('内容规则不能为空');
                    }
                    if ( ! empty($row['html_dir']) && ! Validate::is($row['html_dir'], 'alphaDash')) {
                        $this->error('静态文件保存目录名称只能是字母数字下划线');
                    }

                    $isstatic = 1;

                    Db::name('config')->where(['name' => 'html_dir'])->save(['value' => $row['html_dir']]);
                    Db::name('config')->where(['name' => 'html_column_rules'])->save(['value' => $row['html_column_rules'] == -1 ? $row['html_column_rules'] : $this->htmlRules['category'][$row['html_column_rules'] - 1]]);
                    Db::name('config')->where(['name' => 'html_content_rules'])->save(['value' => $row['html_content_rules'] == -1 ? $row['html_content_rules'] : $this->htmlRules['content'][$row['html_content_rules'] - 1]]);

                    //Cache::tag(ConfigService::CACHE_TAG)->clear();

                    // 更新静态URL地址
                    Html::buildUrl();
                }
            }
            if (($row['category_format'] == -1 && empty($row['category_format_diy'])) || ($row['content_format'] == -1 && empty($row['content_format_diy']))) {
                $this->error('自定义内容不能为空');
            }

            Db::name('config')->where(['name' => 'category_format'])->save(['value' => $row['category_format'] == -1 ? $row['category_format_diy'] : $row['category_format']]);
            Db::name('config')->where(['name' => 'content_format'])->save(['value' => $row['content_format'] == -1 ? $row['content_format_diy'] : $row['content_format']]);
            Db::name('config')->where(['name' => 'url_mode'])->save(['value' => $row['url_mode']]);

            Cache::clear();
            $this->success('操作成功', '', ['isstatic' => $isstatic]);
        }
        $config = ConfigModel::where('group', 'seo')->select();
        $field  = [];
        foreach ($config as $key => $value) {
            $field[$value['name']] = $value['value'];
            if ($value['name'] == 'url_rewrite') {
                $rewrite = json_decode($value['value'], true);
                if ( ! isset($rewrite['index/lists']) || ! isset($rewrite['index/show'])) {
                    continue;
                }
                foreach ($this->rules as $k => $v) {
                    if ($v[0] == $rewrite['index/lists'] && $v[1] == $rewrite['index/show']) {
                        $field[$value['name']] = $k + 1;
                        break;
                    }
                }
            }
        }
        // 获取栏目信息
        $model = CategoryModel::alias('c')->leftJoin('models m', 'm.id=c.model_id')->field('c.*,m.name as model_name');
        $data  = $model->order(['c.sort' => 'asc', 'c.id' => 'asc'])->select()->append(['type_text'])->toArray();

        $category = Tree2::instance()->getTreeList(Tree2::instance()->init($data)->getTreeArray(0));
        View::assign('field', $field);
        View::assign('htmlRules', $this->htmlRules);
        View::assign('category', $category);

        return View::fetch();
    }

    /**
     * 生成整站HTML
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function generation()
    {

    }

}
